package com.ffalcon.mercury.android.sdk.demo

import android.Manifest
import android.app.ActivityManager
import android.content.Intent
import android.content.pm.PackageManager
import android.hardware.Camera
import android.os.Build
import android.os.Bundle
import android.os.Handler
import android.provider.Settings
import android.text.TextUtils
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Toast
import androidx.core.app.ActivityCompat
import androidx.core.app.ActivityOptionsCompat
import androidx.core.content.ContextCompat
import com.ffalcon.mercury.android.sdk.demo.SPUtils.clearSP
import com.ffalcon.mercury.android.sdk.demo.SPUtils.getValue
import com.ffalcon.mercury.android.sdk.demo.SPUtils.putValue
import com.ffalcon.mercury.android.sdk.demo.api.BaseBean
import com.ffalcon.mercury.android.sdk.demo.api.IPInfoBean
import com.ffalcon.mercury.android.sdk.demo.api.IpResponse
import com.ffalcon.mercury.android.sdk.demo.api.RetrofitManager
import com.ffalcon.mercury.android.sdk.demo.databinding.LayoutDemoHomeBinding
import com.ffalcon.mercury.android.sdk.ui.activity.BaseMirrorActivity
import com.king.camera.scan.CameraScan
import com.pedro.common.ConnectChecker
import com.pedro.encoder.input.video.CameraHelper
import com.pedro.library.rtmp.RtmpCamera1
import io.reactivex.rxjava3.android.schedulers.AndroidSchedulers
import io.reactivex.rxjava3.core.Observable
import io.reactivex.rxjava3.disposables.Disposable
import io.reactivex.rxjava3.schedulers.Schedulers
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.runBlocking
import java.util.concurrent.TimeUnit
import kotlin.system.exitProcess


class DemoHomeActivity : BaseMirrorActivity<LayoutDemoHomeBinding>(), SurfaceHolder.Callback,
    ConnectChecker, SocketClient.HeartbeatListener{
    private lateinit var currentDialog: CustomDialog
    private lateinit var disposable: Disposable
    private lateinit var disposable4: Disposable
    private lateinit var disposable5: Disposable
    private val TAG = "VoiceCallApp"
    private lateinit var rtmpCamera1: RtmpCamera1
    val REQUEST_CODE_SCAN = 0X01
    private var ipLocation: String? = ""
    private var mSocketClient: SocketClient? = null
    private val handler: Handler = Handler()
    private var taskId: String? = null
    private var sign: String? = null
    private var rtmpUrl: String? = null
    private val MAX_RECONNECT_TIMES = 10 // 最大重连次数

    private var currentReconnectCount = 0 // 当前重连次数

    private val CAMERA_PERMISSION_REQUEST_CODE = 1001
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        // 初始化时检查并申请相机权限
        checkAndRequestCameraPermission()


    }

    /**
     * 检查并申请相机权限
     */
    private fun checkAndRequestCameraPermission() {
        // 1. 检查相机权限
        val hasCameraPermission = ContextCompat.checkSelfPermission(
            this, Manifest.permission.CAMERA
        ) == PackageManager.PERMISSION_GRANTED

        // 2. 检查麦克风（语音）权限（新增）
        val hasAudioPermission = ContextCompat.checkSelfPermission(
            this, Manifest.permission.RECORD_AUDIO
        ) == PackageManager.PERMISSION_GRANTED

        // 3. 检查存储权限（原有逻辑）
        val needStoragePermission = Build.VERSION.SDK_INT < Build.VERSION_CODES.TIRAMISU
        val hasStoragePermission = if (needStoragePermission) {
            ContextCompat.checkSelfPermission(
                this, Manifest.permission.WRITE_EXTERNAL_STORAGE
            ) == PackageManager.PERMISSION_GRANTED
        } else {
            true // Android 13+ 不需要 WRITE_EXTERNAL_STORAGE
        }

        // 4. 组装需要申请的权限列表（包含新增的语音权限）
        val permissionsToRequest = mutableListOf<String>()
        if (!hasCameraPermission) permissionsToRequest.add(Manifest.permission.CAMERA)
        if (!hasAudioPermission) permissionsToRequest.add(Manifest.permission.RECORD_AUDIO) // 新增
        if (needStoragePermission && !hasStoragePermission) {
            permissionsToRequest.add(Manifest.permission.WRITE_EXTERNAL_STORAGE)
        }

        when {
            // 5. 所有权限已授予
            permissionsToRequest.isEmpty() -> {
                startCameraOperation()
            }
            // 6. 需要解释权限用途（优先解释相机或麦克风权限）
            ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)
                    || ActivityCompat.shouldShowRequestPermissionRationale(
                this,
                Manifest.permission.RECORD_AUDIO
            ) -> {
                Toast.makeText(this, "需要相机和麦克风权限才能进行推流操作", Toast.LENGTH_SHORT)
                    .show()
                ActivityCompat.requestPermissions(
                    this, permissionsToRequest.toTypedArray(), CAMERA_PERMISSION_REQUEST_CODE
                )
            }
            // 7. 直接申请权限
            else -> {
                ActivityCompat.requestPermissions(
                    this, permissionsToRequest.toTypedArray(), CAMERA_PERMISSION_REQUEST_CODE
                )
            }
        }
    }

    /**
     * 权限申请结果回调
     */
    override fun onRequestPermissionsResult(
        requestCode: Int, permissions: Array<out String>, grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE) {
            // 检查是否所有申请的权限都被授予
            val allGranted = grantResults.all { it == PackageManager.PERMISSION_GRANTED }
            when {
                allGranted -> {
                    Toast.makeText(this, "权限申请成功", Toast.LENGTH_SHORT).show()
                    startCameraOperation() // 权限通过，启动相机业务
                }
                // 用户拒绝权限（未勾选"不再询问"）
                permissions.any {
                    ActivityCompat.shouldShowRequestPermissionRationale(this, it)
                } -> {
                    Toast.makeText(this, "请授予相机权限以继续操作", Toast.LENGTH_SHORT).show()
                }
                // 用户拒绝权限并勾选"不再询问"（需要引导用户去设置页开启）
                else -> {
                    Toast.makeText(
                        this, "相机权限已被拒绝，请前往设置页开启", Toast.LENGTH_LONG
                    ).show()
                    // 引导用户跳转到应用设置页
                    val intent = Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS).apply {
                        data = android.net.Uri.fromParts("package", packageName, null)
                    }
                    startActivity(intent)
                }
            }
        }
    }

    // 记录推流状态，用于恢复时判断是否需要重新启动
    private var wasStreaming = false

    // 添加标志位，防止生命周期中重复初始化
    @Volatile
    private var isResuming = false

    @Volatile
    private var isPausing = false

    // 记录最后停止时间，防止快速重启相机导致问题
    private var lastStopTime = 0L
    private val CAMERA_RESTART_DELAY = 500L // 500ms延迟，防止相机快速重启

    override fun onResume() {
        super.onResume()

        // 使用同步块防止并发执行
        synchronized(this) {
            if (isResuming) {
                Log.d(TAG, "已在恢复中，跳过重复调用")
                return
            }
            isResuming = true
        }

        try {
            // 检查是否刚停止相机，如果太短时间就不重新启动
            val timeSinceStop = System.currentTimeMillis() - lastStopTime
            if (lastStopTime > 0 && timeSinceStop < CAMERA_RESTART_DELAY) {
                Log.d(TAG, "停止相机时间过短（${timeSinceStop}ms），跳过恢复相机，延迟恢复")
                synchronized(this) { isResuming = false }
                handler.postDelayed({
                    if (!isFinishing && !isDestroyed) {
                        onResume()
                    }
                }, CAMERA_RESTART_DELAY - timeSinceStop + 50)
                return
            }

            Log.d(TAG, "onResume: 开始恢复相机和推流")

            // 恢复推流 - 在后台线程执行，避免阻塞UI
            if (::rtmpCamera1.isInitialized) {
                CoroutineScope(Dispatchers.IO).launch {
                    try {
                        // 等待Surface准备好后再启动预览
                        // 如果Surface还没准备好，会在surfaceCreated时自动启动预览
                        if (rtmpCamera1.isOnPreview) {
                            Log.d(TAG, "相机预览已在运行")
                        } else {
                            Log.d(TAG, "等待Surface创建后启动预览")
                        }

                        // 如果之前正在推流，则恢复推流
                        if (wasStreaming && !rtmpCamera1.isStreaming && rtmpUrl != null) {
                            rtmpUrl?.let { url ->
                                // 确保麦克风已创建
//                                try {
//                                    rtmpCamera1.createMicrophone()
//                                    Log.d(TAG, "已重新创建麦克风")
//                                } catch (e: Exception) {
//                                    Log.e(TAG, "创建麦克风失败: ${e.message}")
//                                }

                                if (prepareEncoders()) {
                                    rtmpCamera1.startStream(url)
                                    Log.d(TAG, "已恢复推流")
                                }
                            }
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "onResume 时恢复相机操作出错: ${e.message}")
                    }
                }
            }

            Log.d(TAG, "onResume: 完成")
        } finally {
            synchronized(this) {
                isResuming = false
            }
        }
    }

    override fun onPause() {
        super.onPause()

        // 使用同步块防止并发执行
        synchronized(this) {
            if (isPausing) {
                Log.d(TAG, "已在暂停中，跳过重复调用")
                return
            }
            isPausing = true
        }

        try {
            Log.d(TAG, "onPause: 开始停止相机和推流")

            // 停止推流和预览 - 在后台线程执行，避免阻塞UI
            if (::rtmpCamera1.isInitialized) {
                CoroutineScope(Dispatchers.IO).launch {
                    try {
                        if (rtmpCamera1.isStreaming) {
                            wasStreaming = true // 记录当前推流状态
                            rtmpCamera1.stopStream() // 暂停推流
                            Log.d(TAG, "已停止推流")
                        } else {
                            wasStreaming = false
                        }

                        // 停止相机预览（防止向已释放的 SurfaceView 推送数据）
                        if (rtmpCamera1.isOnPreview) {
                            rtmpCamera1.stopPreview()
                            Log.d(TAG, "已停止相机预览")
                        }
                    } catch (e: Exception) {
                        Log.e(TAG, "onPause 时停止相机操作出错: ${e.message}")
                    }
                }
            } else {
                wasStreaming = false
            }

            // 记录停止时间，用于防止快速重启
            lastStopTime = System.currentTimeMillis()

            Log.d(TAG, "onPause: 完成")
        } finally {
            synchronized(this) {
                isPausing = false
            }
        }
    }


    override fun onDestroy() {
        super.onDestroy()
        initRelease()

//        putValue(this, "ipLocation", "")
    }

    private fun initRelease() {

        // 1. 移除 Handler 所有回调（避免内存泄漏+后台任务继续执行）
        handler.removeCallbacksAndMessages(null)

        // 2. 释放 RxJava 所有订阅（防止网络请求/定时任务持有 Activity 引用）
        if (::disposable.isInitialized) { // 确保 compositeDisposable 已初始化
            disposable.dispose()
        }
        if (::disposable4.isInitialized) { // 确保 compositeDisposable 已初始化
            disposable4.dispose()
        }
        if (::disposable5.isInitialized) { // 确保 compositeDisposable 已初始化
            disposable5.dispose()
        }

        // 3. 彻底释放 RTMP 推流/Camera/编码器资源（核心）
        // 在后台线程执行以避免阻塞onDestroy
        if (::rtmpCamera1.isInitialized) {
            runBlocking(Dispatchers.IO) {
                try {
                    Log.d(TAG, "开始释放相机资源")

                    // 先停止推流
                    if (rtmpCamera1.isStreaming) {
                        rtmpCamera1.stopStream()
                        Log.d(TAG, "已停止推流")
                    }

                    // 停止相机预览
                    if (rtmpCamera1.isOnPreview) {
                        rtmpCamera1.stopPreview()
                        Log.d(TAG, "已停止预览")
                    }

                    // 停止录制（如果有）
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2 && rtmpCamera1.isRecording) {
                        rtmpCamera1.stopRecord()
                        Log.d(TAG, "已停止录制")
                    }

                    Log.d(TAG, "相机资源已释放")
                } catch (e: Exception) {
                    Log.e(TAG, "释放相机资源时出错: ${e.message}")
                }
            }
        }


        Log.d(TAG, "Socket 连接已释放")

        // 5. 释放对话框资源（避免对话框持有 Activity 引用导致泄漏）
        if (::currentDialog.isInitialized && currentDialog.isShowing) {
            currentDialog.dismiss()
        }

        // 6. 重置状态变量（避免重建时状态混乱）
        mSocketClient!!.stop();
        currentReconnectCount = 0

        taskId = null
        sign = null


    }

    /**
     * 相机业务逻辑（替换为你的实际需求）
     * 示例：打开系统相机、启动自定义相机预览、初始化扫码库等
     */
    private fun startCameraOperation() {


        ipLocation = getValue(this, "ipLocation", "") as String?

        if (TextUtils.isEmpty(ipLocation)) {

            startScan();
            return;
        }


        val surfaceView = findViewById<SurfaceView>(R.id.surfaceView)

        Log.e(TAG, "----------------" + ipLocation)
        val params = surfaceView.layoutParams
        // 获取屏幕实际宽高（注意：屏幕可能是竖屏，需区分宽高）
        val screenWidth = resources.displayMetrics.widthPixels // 2560px
        val screenHeight = resources.displayMetrics.heightPixels // 1600px
        // 强制 SurfaceView 宽高等于屏幕宽高
        params.width = screenWidth
        params.height = screenHeight
        surfaceView.layoutParams = params // 刷新布局参数


        surfaceView.holder.addCallback(this)

        rtmpCamera1 = RtmpCamera1(surfaceView, this)


    }

    private fun prepareEncoders(): Boolean {
        try {
            val resolutionsBack: List<Camera.Size> = rtmpCamera1.resolutionsBack
            val resolution: Camera.Size = resolutionsBack[0]
            val width = resolution.width
            val height = resolution.height
            var prepareVideo = rtmpCamera1.prepareVideo(
                width, height, 15, 1024 * 300, 2, 0
            )
            var prepareAudio = rtmpCamera1.prepareAudio(
                64 * 1024, 44100, true, false, false
            )

            Log.d(TAG, "prepareEncoders: video=$prepareVideo, audio=$prepareAudio")

            return prepareVideo && prepareAudio
        } catch (e: Exception) {
            Log.e(TAG, "prepareEncoders 失败: ${e.message}")
            return false
        }
    }

    private fun startScan() {


        val optionsCompat = ActivityOptionsCompat.makeCustomAnimation(this, R.anim.`in`, R.anim.out)
        val intent = Intent(this, QRCodeScanActivity::class.java)
        ActivityCompat.startActivityForResult(
            this, intent, REQUEST_CODE_SCAN, optionsCompat.toBundle()
        )
    }


    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK && data != null) {
            when (requestCode) {
                REQUEST_CODE_SCAN -> {
                    val result = CameraScan.parseScanResult(data)

                    if (result == null || !isValidIp(result)) {
                        Toast.makeText(this, "输入的 IP 地址或推流地址无效", Toast.LENGTH_SHORT)
                            .show()
                        return
                    }


                    Toast.makeText(this, "成功", Toast.LENGTH_SHORT).show();


                    if (result != null) {
                        putValue(this, "ipLocation", result)
                    }
                    Log.e(TAG, "onActivityResult: ");
                    startCameraOperation();
                }


            }
        }
    }
    // 工具方法：强制结束指定Activity

    private fun isValidIp(ip: String): Boolean {
        return !TextUtils.isEmpty(ip) && UrlValidator.isValidUrl(ip)
    }

    private fun startReconnect() {
        // 检查 Activity 是否还在运行
        if (isFinishing || isDestroyed) {
            Log.d(TAG, "Activity 已销毁，取消重连")
            return
        }

        currentReconnectCount++
        if (currentReconnectCount <= MAX_RECONNECT_TIMES) {
            handler.postDelayed({
                // 再次检查 Activity 状态
                if (isFinishing || isDestroyed) {
                    Log.d(TAG, "Activity 已销毁，取消重连回调")
                    return@postDelayed
                }

                Log.d(
                    "RTMP_RECONNECT",
                    "连接失败，开始第 $currentReconnectCount 次重连"
                )
                initUrl() // 重新初始化连接
            }, 5000) // 重连间隔5秒
        } else {
            Log.e("RTMP_RECONNECT", "达到最大重连次数，停止重连")
            currentReconnectCount = 0 // 重置计数器
            if (::rtmpCamera1.isInitialized && rtmpCamera1.isStreaming) {
                try {
                    rtmpCamera1.stopStream()
                    Log.d(TAG, "停止推流")
                } catch (e: Exception) {
                    Log.e(TAG, "停止重连时停止推流出错: ${e.message}")
                }
            }
            // 不再显示Toast，避免过多提示
        }
    }

    private fun initUrl() {
        if (!::rtmpCamera1.isInitialized) return
        Log.d("TAG_R", "b_start_stop: ")
        if (!rtmpCamera1.isStreaming) {
            if (prepareEncoders()) {

                if (!TextUtils.isEmpty(rtmpUrl) && ::rtmpCamera1.isInitialized) {
                    // 在子线程启动推流（避免阻塞主线程）
                    CoroutineScope(Dispatchers.IO).launch {
                        try {
                            // 确保麦克风已创建
//                                    rtmpCamera1.createMicrophone()
//                                    Log.d(TAG, "已创建麦克风")

                            rtmpCamera1.startStream(rtmpUrl)
                            Log.d(TAG, "已启动推流")
                        } catch (e: Exception) {
                            Log.e(TAG, "启动推流失败: ${e.message}")
                        }


                    }
                    return
                }
//                rtmpCamera1.startStream("rtmp://192.168.40.128:1935/live/test");
                disposable = RetrofitManager.getApiService().getIp("")
                    .subscribeOn(Schedulers.io())
                    .observeOn(Schedulers.io()) // 子线程解析
                    .map { response ->
                        // 简化解析逻辑，利用空安全操作符
                        response.getData()
                            .firstOrNull { it.sign == "rtmpGlassesUrl" }
                            ?.let { bean ->
                                taskId = bean.taskId
                                sign = bean.sign
                                bean.ipUrl // 若找到，返回非空 url
                            }!!
                    }
                    .observeOn(AndroidSchedulers.mainThread()) // 主线程更新 UI
                    .subscribe({ rtmpUrl1 ->
                        if (!TextUtils.isEmpty(rtmpUrl1) && ::rtmpCamera1.isInitialized) {
                            // 在子线程启动推流（避免阻塞主线程）
                            CoroutineScope(Dispatchers.IO).launch {
                                try {
                                    // 确保麦克风已创建
//                                    rtmpCamera1.createMicrophone()
//                                    Log.d(TAG, "已创建麦克风")
                                    rtmpUrl = rtmpUrl1;
                                    rtmpCamera1.startStream(rtmpUrl1)
                                    Log.d(TAG, "已启动推流")
                                } catch (e: Exception) {
                                    Log.e(TAG, "启动推流失败: ${e.message}")
                                }
                            }
//                            runOnUiThread {
//                                Toast.makeText(this, "开始推流", Toast.LENGTH_SHORT).show()
//                            }
                        } else {
//                            runOnUiThread {
//                                Toast.makeText(this, "推流地址无效", Toast.LENGTH_SHORT).show()
//                            }
                        }
                    }, { throwable ->
                        Log.e("MediaService", "获取推流地址失败：${throwable.message}")
//                        runOnUiThread {
//                            Toast.makeText(this, "推流地址获取失败", Toast.LENGTH_SHORT).show()
//                        }
                    })
                Log.e("MediaService", "--------------------3 ")
            } else {
//                runOnUiThread {
//                    Toast.makeText(
//                        this, "准备流时出错，此设备无法执行此操作",
//                        Toast.LENGTH_SHORT
//                    ).show()
//                }
            }
        } else {
            try {
                rtmpCamera1.stopStream()
            } catch (e: Exception) {
                Log.e(TAG, "停止推流时出错: ${e.message}")
            }
        }
    }
    /**
     * socket  心跳检测
     */
    private fun initSocket() {
        // 初始化Socket客户端并设置回调
        val protocolEnd = ipLocation!!.indexOf("://")
        val remaining = ipLocation!!.substring(protocolEnd + 3) // 从 "://" 后面开始截取

        // 步骤2：去掉端口部分（从 ":" 处分割）
        val portStart = remaining.indexOf(":")
        val ip = remaining.substring(0, portStart) // 截取到 ":" 之前的部分
        mSocketClient = SocketClient(this, ip, taskId)
        mSocketClient!!.start() // 启动连接
    }
    private fun setSendMSG(b: Boolean) {
        if (taskId == null) {
            return
        }

        // 检查Activity是否正在销毁，如果是则不初始化Socket
        if (isFinishing || isDestroyed || isPausing) {
            Log.d(TAG, "Activity正在暂停或销毁，跳过Socket初始化")
            return
        }
//        initSocket()

        val map: MutableMap<Any, Any> = HashMap()
        map["taskId"] = taskId!!
        map["sign"] = sign!!
        //        map.put("id", "");
        if (b) map["status"] = "1" else map["status"] = "0"
        disposable4 = RetrofitManager.getApiService().setState(map)
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe(
                { response: IpResponse ->
                    println(
                        "---------------------Received response: $response"
                    )
                }
            ) { throwable: Throwable ->
                System.err.println("Error occurred: " + throwable.message)
                Log.e("--------MediaService", "Video upload failed: " + throwable.message)
            }
    }


    override fun surfaceCreated(holder: SurfaceHolder) {
        Log.d(TAG, "surfaceCreated: Surface已创建")

        // 先启动相机预览
        if (::rtmpCamera1.isInitialized && !rtmpCamera1.isOnPreview) {
            try {
                rtmpCamera1.startPreview(CameraHelper.Facing.BACK, 0)
                Log.d(TAG, "surfaceCreated: 已启动相机预览")
            } catch (e: Exception) {
                Log.e(TAG, "surfaceCreated: 启动相机预览失败: ${e.message}")
            }
        }

        // 在后台线程执行网络请求，避免阻塞UI
        CoroutineScope(Dispatchers.IO).launch {
            initUrl()
        }
    }

    override fun surfaceChanged(holder: SurfaceHolder, format: Int, width: Int, height: Int) {
        // 在 surfaceChanged 中打印日志
        Log.d(TAG, "Surface 宽高：$width x $height")
        Log.d(
            TAG,
            "屏幕宽高：${resources.displayMetrics.widthPixels} x ${resources.displayMetrics.heightPixels}"
        )

        // Surface已准备好，可以启动预览
        if (::rtmpCamera1.isInitialized && !rtmpCamera1.isOnPreview) {
            try {
                rtmpCamera1.startPreview(CameraHelper.Facing.BACK, 0)
                Log.d(TAG, "surfaceChanged: 已启动相机预览")
            } catch (e: Exception) {
                Log.e(TAG, "surfaceChanged: 启动相机预览失败: ${e.message}")
            }
        }
    }

    override fun surfaceDestroyed(p0: SurfaceHolder) {
        if (!::rtmpCamera1.isInitialized) return

        Log.d(TAG, "surfaceDestroyed: Surface 已销毁")

        // 在后台线程执行停止操作，避免阻塞UI
        CoroutineScope(Dispatchers.IO).launch {
            try {
                // Surface 被销毁时停止所有操作
                if (rtmpCamera1.isStreaming) {
                    rtmpCamera1.stopStream()
                    Log.d(TAG, "surfaceDestroyed: 已停止推流")
                }

                if (rtmpCamera1.isOnPreview) {
                    rtmpCamera1.stopPreview()
                    Log.d(TAG, "surfaceDestroyed: 已停止预览")
                }


            } catch (e: Exception) {
                Log.e(TAG, "surfaceDestroyed 时出错: ${e.message}")
            }
        }
    }


    override fun onAuthError() {

    }

    override fun onAuthSuccess() {
//        Toast.makeText(this, "Auth success", Toast.LENGTH_SHORT).show();
    }

    override fun onConnectionFailed(reason: String) {
        Log.e(TAG, "RTMP连接失败: $reason")
        if (::rtmpCamera1.isInitialized && rtmpCamera1.isStreaming) {
            try {
                rtmpCamera1.stopStream()
                Log.d(TAG, "已停止推流")
            } catch (e: Exception) {
                Log.e(TAG, "连接失败时停止推流出错: ${e.message}")
            }
        }
        // 不触发重连，由SocketClient自动重连
    }

    override fun onConnectionStarted(url: String) {

    }

    private fun startTimer() {
        handler.postDelayed({
            if (rtmpCamera1.isStreaming) { // 仅在页面可见时执行
                Log.e(TAG, "111111111111   正在推流中...")

                // 移除Toast，避免每3秒显示一次导致资源加载问题
                runOnUiThread {
                    try {
                        Toast.makeText(this, "正在推流中...", Toast.LENGTH_SHORT).show()
                    } catch (e: Exception) {
                        Log.e(TAG, "显示Toast失败: ${e.message}")
                    }
                }
                startTimer()
            }
        }, 3000)
    }

    override fun onConnectionSuccess() {
        currentReconnectCount = 0
        initGetList()
        runOnUiThread {
            Log.e(TAG, "111111111111   连接成功...")
            try {
                Toast.makeText(this, "连接成功", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                Log.e(TAG, "显示Toast失败: ${e.message}")
            }
            setSendMSG(true)
            startTimer()
        }
    }

    private fun initGetList() {
        disposable5 = Observable.interval(0, 10, TimeUnit.SECONDS)
            .flatMapSingle { aLong ->
                RetrofitManager.getApiService()
                    .info
            }
            .subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
            .subscribe({ response ->
                // 处理响应数据
                println("---------------------Received response: $response")
                if (response.getCode() !== 200 || response.getData() == null) {
                    return@subscribe
                }
                if (response.getData().getType().equals("1")) {
                    val dialog = CustomDialog(this)
                    dialog.setText(response.getData().getText())
                    showDialog(dialog)
                } else if (response.getData().getType().equals("2")) {
                    val imageDialog = CustomDialog(this)
                    imageDialog.setImageUrl(response.getData().getFilePath())
                    showDialog(imageDialog)
                } else if (response.getData().getType().equals("3")) {
                    val videoDialog = CustomDialog(this)
                    videoDialog.setVideoUrl(
                        response.getData().getFilePath()
                    )
                    showDialog(videoDialog)
                }
            }) { throwable ->
                // 处理错误l
//                System.err.println("---------------------Error occurred: " + throwable.getMessage())
            }
    }

    private fun showDialog(dialog: CustomDialog) {
        // 关闭旧对话框
        if (currentDialog != null && currentDialog.isShowing()) {
            currentDialog.dismiss()
        }
        // 显示新对话框并保存实例
        currentDialog = dialog
        dialog.show()
    }

    override fun onDisconnect() {

        // 只有在Activity活跃时才记录断开状态，不触发重连
        startReconnect(); // 瑙﹀彂閲嶈繛
    }
    override fun onConnected() {
        Log.d(TAG, "连接成功")
    }

    override fun onDisconnected() {
        Log.d(TAG, "连接断开，正在重连...")
    }

    override fun onHeartbeatSuccess() {
        Log.d(TAG, "心跳正常")
    }

    override fun onHeartbeatFailed() {
        Log.d(TAG, "心跳失败")
    }

    override fun onReceiveMessage(message: String) {
        Log.d(TAG, "收到消息$message")
    }

    override fun onReady() {
        Log.d(TAG, "已收到READY，开始心跳")
        // 可以在这里执行后续操作，如发送业务数据
    }

}